import tkinter as tk
from tkinter import ttk, messagebox


class GradeApp:
    def __init__(self, root):
        self.root = root
        self.root.title("成绩管理系统")

        self.data = [
            {"id_no": 9001, "name": "张飞", "course": "语言", "score": 90, "class": "科创一班", "year": 2022},
            {"id_no": 9002, "name": "关羽", "course": "数学", "score": 85, "class": "科创二班", "year": 2023},
            {"id_no": 9003, "name": "赵云", "course": "英语", "score": 92, "class": "科创一班", "year": 2022},
            {"id_no": 9004, "name": "马超", "course": "物理", "score": 88, "class": "科创三班", "year": 2023},
            {"id_no": 9005, "name": "黄忠", "course": "化学", "score": 95, "class": "科创二班", "year": 2022}
        ]

        # 搜索框
        self.search_frame = tk.Frame(self.root)
        self.search_frame.pack(pady=5)
        tk.Label(self.search_frame, text="学生编号：").pack(side=tk.LEFT)
        self.search_entry = tk.Entry(self.search_frame)
        self.search_entry.pack(side=tk.LEFT, padx=5)
        tk.Button(self.search_frame, text="搜索", command=self.search_data).pack(side=tk.LEFT)

        # 表格
        self.tree = ttk.Treeview(self.root, columns=("id_no", "name", "course", "score", "class", "year"),
                                 show="headings")
        self.tree.heading("id_no", text="学生编号")
        self.tree.heading("name", text="姓名")
        self.tree.heading("course", text="课程")
        self.tree.heading("score", text="成绩")
        self.tree.heading("class", text="班级")
        self.tree.heading("year", text="年度")
        self.tree.pack()
        self.load_data()

        # 操作按钮
        btn_frame = tk.Frame(self.root)
        btn_frame.pack(pady=10)
        tk.Button(btn_frame, text="新增", command=self.show_add_window).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="修改", command=self.show_edit_window).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="删除", command=self.delete_data).pack(side=tk.LEFT, padx=5)

    def load_data(self):
        for item in self.tree.get_children():
            self.tree.delete(item)

        for record in self.data:
            self.tree.insert("", "end", values=(
                record["id_no"],
                record["name"],
                record["course"],
                record["score"],
                record["class"],
                record["year"]
            ))

    def search_data(self):
        search_id = self.search_entry.get()
        if not search_id:
            self.load_data()
            return
        filtered = [item for item in self.data if str(item["id_no"]) == search_id]
        self.data = filtered
        self.load_data()

    def show_add_window(self):
        add_win = tk.Toplevel(self.root)
        add_win.title("新增数据")

        fields = ["学生编号", "姓名", "课程", "成绩", "班级", "年度"]
        for i, field in enumerate(fields):
            tk.Label(add_win, text=field).grid(row=i, column=0, padx=5, pady=2)
            tk.Entry(add_win).grid(row=i, column=1, padx=5, pady=2)

        tk.Button(add_win, text="确定", command=lambda: self.save_add_data(add_win)).grid(row=6, column=0, columnspan=2,
                                                                                          pady=5)

    def save_add_data(self, win):
        new_data = {
            "id_no": win.grid_slaves(row=0, column=1)[0].get(),
            "name": win.grid_slaves(row=1, column=1)[0].get(),
            "course": win.grid_slaves(row=2, column=1)[0].get(),
            "score": win.grid_slaves(row=3, column=1)[0].get(),
            "class": win.grid_slaves(row=4, column=1)[0].get(),
            "year": win.grid_slaves(row=5, column=1)[0].get()
        }
        self.data.append(new_data)
        self.load_data()
        win.destroy()

    def show_edit_window(self):
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("提示", "请选择要修改的记录")
            return
        index = self.tree.index(selected[0])
        old_data = self.data[index]

        edit_win = tk.Toplevel(self.root)
        edit_win.title("修改数据")

        fields = ["id_no", "name", "course", "score", "class", "year"]
        for i, field in enumerate(fields):
            tk.Label(edit_win, text=field).grid(row=i, column=0, padx=5, pady=2)
            entry = tk.Entry(edit_win)
            entry.insert(0, old_data[field.lower().replace(" ", "_")])
            entry.grid(row=i, column=1, padx=5, pady=2)

        tk.Button(edit_win, text="确定", command=lambda: self.save_edit_data(edit_win, index)).grid(row=6, column=0,
                                                                                                    columnspan=2,
                                                                                                    pady=5)

    def save_edit_data(self, win, index):
        new_data = {
            "id_no": win.grid_slaves(row=0, column=1)[0].get(),
            "name": win.grid_slaves(row=1, column=1)[0].get(),
            "course": win.grid_slaves(row=2, column=1)[0].get(),
            "score": win.grid_slaves(row=3, column=1)[0].get(),
            "class": win.grid_slaves(row=4, column=1)[0].get(),
            "year": win.grid_slaves(row=5, column=1)[0].get()
        }
        self.data[index] = new_data
        self.load_data()
        win.destroy()

    def delete_data(self):
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("提示", "请选择要删除的记录")
            return
        if messagebox.askyesno("确认", "确认删除？"):
            index = self.tree.index(selected[0])
            del self.data[index]
            self.load_data()


if __name__ == "__main__":
    root = tk.Tk()
    app = GradeApp(root)
    root.mainloop()